<template>
  <div class="edit">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{title}}</span>
        <el-button @click="$router.go(-1)" style="float: right; padding: 3px 0" type="text">返回</el-button>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="图片" prop="imageUrl">
          <Upload v-model="form.imageUrl" @clear="clearImageValidate" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="跳转地址" prop="linkUrl">
          <el-input v-model="form.linkUrl"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import Upload from "@/components/Upload";
import { getBanner, addBanner, updateBanner } from "@/api/system/banner";

export default {
  name: "BannerEdit",
  components: {
    Upload
  },
  data() {
    return {
      title: "添加轮播图",
      // 表单参数
      form: {
        name: "",
        imageUrl: "",
        linkUrl: ""
      },
      // 表单校验
      rules: {
        imageUrl: [{ required: true, message: "请上传图片" }],
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        linkUrl: [
          {
            pattern: /[a-zA-z]+:\/\/[^\s]*/,
            message: "请输入正确的链接地址",
            trigger: "blur"
          }
        ]
      }
    };
  },
  mounted() {
    this.getEditInfo();
  },
  methods: {
    clearImageValidate() {
      this.rules.imageUrl = [];
      this.$refs["form"].clearValidate("imageUrl");
    },
    getEditInfo() {
      const id = this.$route.query.id;
      if (id) {
        getBanner(id).then(response => {
          this.form = response.data;
        });
        this.title = "修改轮播图";
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBanner(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.$router.go(-1);
              }
            });
          } else {
            addBanner(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("添加成功");
                this.$router.go(-1);
              }
            });
          }
        }
      });
    },
    // 重置按钮
    cancel() {
      this.getEditInfo();
      this.resetForm("form");
    }
  }
};
</script>
